package com.jnshu.tools.binding;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;



/**
 * @author Martin
 * @date 2019/8/9 21:07
 */
@Slf4j
public class AliSmsUtil {
    //产品名称，云通信短信API产品，开发者无需替换；
    private static final String product = "Dysmsapi";
    //产品域名，开发者无需替换
    private static final String domain = "dysmsapi.aliyuncs.com";
    //id和sercret需替换
    private static final String accessKeyId = "";
    private static final String accessKeySecret = "";
    private static final String signName = "DayDayUp";
    private static final String templateCode = "SMS_167531357";
    private static final String connectTimeout = "10000";
    private static final String readTimeout = "10000";

    /**
     * @param phoneNumber  发送的手机号
     * @return
     * @throws ClientException
     */
    public static Boolean sendSms(String phoneNumber,String randomCode) throws ClientException{

        //可自主调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout",connectTimeout);
        System.setProperty("sun.net.client.defaultReadTimeout",readTimeout);

        //初始化acsClient，暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",accessKeyId,accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou",product,domain );
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述参见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填：待发送手机号码
        request.setPhoneNumbers(phoneNumber);
        //必填：短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填：短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选：模板中的变量替换JSON串，如模板内容为："亲爱的${name},您的验证码为${code}"时，
        //此处的值为："{\"name\":\"张三\",\"code\":\"1234\"}";
        request.setTemplateParam("{\"code\":\""+randomCode+"\"}");

        //选填：上行短信扩展码（无特殊需求用户可忽略此字段）
        //request.setSmsUpExtendCode("123456");

        //可选：outId为提供给业务方的扩展字段，最终在短信回执消息中将此值待会给调用者
        request.setOutId("yourOutId");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("ok")){
            //获取回执ID
            sendSmsResponse.getBizId();
            //请求成功
            return true;
        }else {
            return false;
        }
    }
}
